package org.gongliang.jfinal.controller.sys;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.PasswordMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.gongliang.common.shiro.ShiroDbRealm;
import org.gongliang.jfinal.common.KConstant;
import org.gongliang.jfinal.common.annotation.Logs;
import org.gongliang.jfinal.common.base.Conditions;
import org.gongliang.jfinal.common.base.Result;
import org.gongliang.jfinal.common.exception.ExceptionEnum;
import org.gongliang.jfinal.common.interceptor.LoginValidate;
import org.gongliang.jfinal.controller.BaseController;
import org.gongliang.jfinal.model.Resources;
import org.gongliang.jfinal.model.User;

import com.jfinal.aop.Before;

import com.jfinal.aop.Clear;
import com.jfinal.core.ActionKey;
import com.jfinal.ext.interceptor.LogInterceptor;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.ext.plugin.shiro.ShiroInterceptor;
import com.jfinal.json.JFinalJson;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;

public class UserController extends BaseController<User>{

	private ShiroDbRealm shiroDbRealm  = new ShiroDbRealm();
	public void main() {
		render("/views/sys/User/main.html");
	}

	public void rolePage() {
		setAttr("userId", getPara("userId"));
		render("/views/sys/User/role.html");
	}

	public void updatePage() {
		render("/views/sys/User/user.html");
	}

	@ActionKey("/getMenu")
   public void getUserPermission(){
		Result result = Result.success("查找用户权限成功!");
		User user=getUser();
		List<Record> menuLis=getSessionAttr("menuList");
		if(null==menuLis&&user!=null){
			
			menuLis=Resources.dao.findUserPermission(user.getId(),1);
			setSessionAttr("menuList", menuLis);
		}
		result.setRows(menuLis);
		render(new JsonRender(JFinalJson.getJson().toJson(result)).forIE());
	}
	
	
	public void getPermissionStringList(){
		Result result = Result.success("查找用户权限成功!");
		User user=getUser();
		List<String> permissionList=getSessionAttr("permissionList");
		if(null==permissionList&&user!=null){
			AuthorizationInfo authorizationInfo = shiroDbRealm.doGetAuthorizationInfo(SecurityUtils.getSubject().getPrincipals()) ;
			permissionList=castSetToList((HashSet<String>) authorizationInfo.getStringPermissions());
			setSessionAttr("permissionList", permissionList);
		}
		result.setRows(permissionList);
		renderJson(JFinalJson.getJson().toJson(permissionList));
	}
	
	private List<String> castSetToList(HashSet<String> sets){
		List<String> list = new ArrayList<String>();
		if(sets==null||sets.size()==0) {
			return list;
		}
		for (String str : sets) {  
			list.add(str);
		}
		return list;
	}

	
	@Before(LoginValidate.class)
	@Clear(ShiroInterceptor.class)

	@ActionKey("/sys/login")
	@Logs(des = "用户登录")
	public void login() {

		  //构造tocken
		UsernamePasswordToken token = new UsernamePasswordToken(getPara("username"), getPara("password"));
		
		System.out.println(getPara("password"));
		Subject subject = SecurityUtils.getSubject();
		PasswordMatcher p;
        ThreadContext.bind(subject);
		
		Result result = Result.success("用户登录成功!");
		try {
			subject.login(token);
			User user = (User) subject.getPrincipal();
			setSessionAttr(KConstant.USER_SESSION, user);
			
		} catch (AuthenticationException e) {
			
			result = Result.error(e.getMessage());
		}
		

		render(new JsonRender(result).forIE());
	}
	@ActionKey("/index")
	public void index(){
		User user=getUser();
		if(user==null){
			System.out.println("-------------------------");
			setAttr("msg", "session过期!");
			render("/views/login.html");
		}else{
			render("/views/index.html");
		}
	}

	public void saveORupdate(){
		Result result = Result.success();
		User m = getBean(User.class, "");
		boolean flag=false;
		
		if(m.getId()!=null){
			flag=m.update();
		}else{
			String password = m.getPassword();
			if(StrKit.notBlank(password)){
				m.setPassword( HashKit.md5(HashKit.sha1(m.getUsername()+password)));
			}
			if(StrKit.isBlank(password)){
				m.setPassword( HashKit.md5(HashKit.sha1(m.getUsername()+"123456")));
			}
			m.setCreateDate(new Date());
			flag=m.save();
		}
		if(flag){
			result.setExceptionEnum(ExceptionEnum.INSERT_SUCCESS);
			render(new JsonRender(result).forIE());
		}else{
			result.setExceptionEnum(ExceptionEnum.INSERT_ERROR);
			render(new JsonRender(result).forIE());
		}
	}
	
	@ActionKey("/sys/logout")
	public void logout(){
		getSession().removeAttribute("loginUser");
		getSession().removeAttribute("menuList");
		getSession().invalidate();
		render("/views/login.html");
	}

	@ActionKey("/sys/unauthc")
	public void unauthcPage() {
		render("/public/error/unauthc.html");
	}
	@ActionKey("/sys/updatePwdPage")
	public void updatePwdPage() {
		render("/views/password.html");
	}

	public void updatePassword(){
		User user=getUser();
		Result result = Result.success("密码修改成功!");
		if(StrKit.isBlank(getPara("newPassword"))){
			render(new JsonRender("新密码不能为空!").forIE());
			return;
		}
		user.set("password", HashKit.md5(HashKit.sha1(user.getUsername()+getPara("newPassword"))));
		if(!user.update()){
			result = Result.error("密码修改失败!");
			render(new JsonRender(result).forIE());
		}else{
			render(new JsonRender(result).forIE());
		}
		
	}
	public void updateUserLocked(){
		User user=User.dao.findById(getPara("id"));
		Result result = Result.success("修改成功!");
		if(user==null) {
			result=Result.error("没有此用户!");
		}
		if(getPara("locked")=="1") {
			user.setLocked(true);
		}else {
			user.setLocked(false);
		}
		
		if(!user.update()){
			result = Result.error("锁定失败!");
			render(new JsonRender(result).forIE());
		}else{
			render(new JsonRender(result).forIE());
		}
		
	}

	@Override
	public String getSql() {
		Conditions condi = new Conditions();
		User user=new User();
		// user.setEmail(getPara("name"));
		user.setUsername(getPara("username"));
		user.setName(getPara("name"));
		user.setStatus(getPara("status"));
		// user.setPhone(getPara("name"));
		user.setCreateDate(null);
    	condi.setValueQuery(Conditions.GREATER_EQUAL, "inputTime", getPara("startTime")); //开始时间
    	condi.setValueQuery(Conditions.LESS_EQUAL, "inputTime", getPara("endTime")); //结束时间
		condi.setFiledQuery(Conditions.FUZZY, "phone", "name", "username", "email");
    	condi.modelToCondition(user,"u");
    	params.clear();
    	params.addAll(condi.getParamList());
    	String sql="select u.*,d.dept_name from sys_user u left join sys_department d on u.dept_id=d.id  ";
		return sql+condi.getSql();
	}
}
